import { expect } from '@jest/globals';
import * as fse from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { decompressHarAndDoSomeThing, readJson5 } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

/**
 * 测试工程选项
 *
 * @type {{template: ProjectTemplateOption}}
 */
const projectBuilderOption: ProjectBuildOption = {
  template: {
    /**
     * 单框架
     */
    sdk: SDKType.Single,

    /**
     * HarmonyOS运行时
     */
    runtimeOS: RuntimeOSType.HarmonyOS,

    /**
     * api10
     */
    apiVersion: APIVersion.API10,

    /**
     * stage模型
     */
    apiType: APIType.STAGE,

    /**
     * ArkTs语言
     */
    language: LanguageType.ArkTs,

    /**
     * app工程
     */
    abilityType: AbilityType.Application,

    /**
     * 模板类型
     */
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    /**
     * SharedLibrary
     */
    [ModuleTemplateType.SharedLibrary]: 1

  }
};

/**
 * 测试用例选项
 *
 * @type {{ohpmInstall: IsEnable, sign: SignType, caseLevel: CaseLevel}}
 */
const taskConfig: TestTaskOption = {
  /**
   * 测试用例级别 L0
   */
  caseLevel: CaseLevel.L1,

  /**
   * 不需要签名文件
   */
  sign: SignType.NoSign,

  /**
   * 不需要执行ohpm install
   */
  ohpmInstall: IsEnable.DisAble
};

/**
 * 测试函数
 *
 * @param {Project} project 测试工程对象
 * @param {TestTaskOption} taskConfig 测试操作可选项
 * @param {ICaseRecord} record 测试记录
 * @return {Promise<void>}
 */
const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 测试工程主目录路径
  const projectRoot = project.projectRootPath();

  // 需要执行的命令行参数
  const commands = initExecuteCommand({
    buildMode: 'release',
    mode: 'module',
    product: 'default',
    tasks: 'assembleHsp',
    module: 'shareLibrary@default'
  });

  const result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('release模式构建shared library', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 检查build下生成.har包、.hsp包和.tgz包
  const hspPath = project.getModule('shareLibrary').moduleRootPath();
  const outputs = path.resolve(hspPath, 'build/default/outputs/default');

  const outputsFiles = await fse.readdir(outputs);
  expect(outputsFiles.some(item => item.includes('.har'))).toBe(true);
  expect(outputsFiles.some(item => item.includes('.hsp'))).toBe(true);
  expect(outputsFiles.some(item => item.includes('.tgz'))).toBe(true);

  // har包内的oh-package.json5文件oh-package.json5的packageType为InterfaceHar
  const harPath = outputsFiles.find((item => item.includes('.har')));
  expect(harPath !== undefined).toBe(true);
  await decompressHarAndDoSomeThing(harPath!, async (target) => {
    const ohPackageJson5 = await readJson5(path.resolve(target, 'oh-package.json5'));

    // 使用断言判断shareLibrary模块oh-package.json5中packageType的值
    expect(ohPackageJson5.packageType).toEqual('InterfaceHar');
  });
};


// 将demo测试用例注册到测试用例中心
TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_DevEco_Studio_Build_HspPackageManagement_01')
  .description('01、新建stage工程，添加shared library，构建shared library，检查构建hsp产物')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
